const secret = "secret"; //
const cookieKey = "token";
const jwt = require("jsonwebtoken");

// 颁发jwt
exports.publish = (res, result, maxAge = "24h", info = {}) => {
	const token = jwt.sign(info, secret, { expiresIn: maxAge });
	res.cookie(cookieKey, token, { maxAge: 3600 * 24 * 1000, patch: "/" });
	res.header("authorization", token);
	result.token = token;
};
// 验证jwt
exports.verify = (req) => {
	let token;
	token = req.cookies[cookieKey];
	if (!token) {
		token = req.headers.authorization;
		if (!token) {
			return null;
		}
		token = token.split(" ");
		token = token.length === 1 ? token[0] : token[1];
	}
	try {
		const result = jwt.verify(token, secret);
		return result;
	} catch (error) {
		return null;
	}
};
